package com.feri.ssm.utils;

import org.springframework.scheduling.concurrent.DefaultManagedAwareThreadFactory;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Feri
 * @date 2021/12/14 20:31
 * @description:TODO
 */
public class MyTask {
    //定义任务类对象
    private static class Task{
        //任务名称
        private String name;
        //任务需要执行的事情，采用线程的模式
        private Runnable runnable;
    }
    //存储提交的任务信息
    private static ConcurrentHashMap<Task,Integer> tasks;
    //创建线程池对象
    private ThreadPoolExecutor executor=new ThreadPoolExecutor(4,
            10,3, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10),new DefaultManagedAwareThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());


    //新增任务
    public void submitTask(Task task,int priority){
        //新增任务
        tasks.put(task,priority);
    }
    //获取任务，按照优先级的获取
    public Task getTask(){
        //使用Lock保证线程安全
        Lock lock=new ReentrantLock();
        try {
            //加锁
            if(lock.tryLock()){
                //对优先级排序
                List<Integer> nums= (List<Integer>) tasks.values();
                Collections.sort(nums);
                Task maxTask=null;
                //遍历获取最大的
                for(Task task:tasks.keySet()){
                    //比较是否优先级最高
                    if(tasks.get(task)== nums.get(nums.size()-1)){
                        maxTask=task;
                        //删除原来数据
                        tasks.remove(task);
                        break;
                    }
                }
                return maxTask;
            }
        }finally {
            //释放锁
            lock.unlock();
        }
        return null;
    }

}
